package com.anssy.voteballot.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.anssy.voteballot.MainActivity;
import com.anssy.voteballot.constant.ConstantValue;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;

import java.io.File;
import java.util.List;


public class CurrencyUtils {

    public static void goToHomeActivity(Activity activity) {
        activity.startActivity(new Intent(activity, MainActivity.class));
        activity.finish();
    }

    public static void showLoading(Activity activity) {
        if (activity != null) {
//            LoadingDialog loadingDialog = LoadingUtils.showLoading(activity);
        }
    }


    /**
     * 是否登录
     *
     * @return
     */
    public static boolean isLogin() {
        String token = SPUtils.getInstance(ConstantValue.SP_NAME, Context.MODE_PRIVATE).getString(ConstantValue.SP_TOKEN);
        if (TextUtils.isEmpty(token)) {
            return false;
        } else {
            return true;
        }
    }

    public static String getToken() {
        String token = SPUtils.getInstance(ConstantValue.SP_NAME, Context.MODE_PRIVATE).getString(ConstantValue.SP_TOKEN);
        if (!TextUtils.isEmpty(token)) {
            return token;
        } else {
            return null;
        }
    }

    public static SPUtils getSpUtils() {
        return SPUtils.getInstance(ConstantValue.SP_NAME, Context.MODE_PRIVATE);
    }

/*    public static void checkToken(String resultMsg, Activity activity) {
        if (resultMsg.contains(ConstantValue.TOKEN_ERROR)) {
            ToastUtils.showShort(ConstantValue.TOKEN_ERROR_HINT);
            SPUtils.getInstance(ConstantValue.SP_NAME, Context.MODE_PRIVATE).clear();
            Intent intent = new Intent(activity, MainActivity.class);
            intent.putExtra(ConstantValue.EXIT_FLAG, "1");
            activity.startActivity(intent);
            activity.finish();
        }



    *//*    if (resultMsg.contains(ConstantValue.TOKEN_ERROR)) {
            ToastUtils.showShort(ConstantValue.TOKEN_ERROR_HINT);
            SPUtils.getInstance(ConstantValue.SP_NAME, Context.MODE_PRIVATE).clear();
            activity.startActivity(new Intent(activity, LoginActivity.class));
            activity.finish();
        }*//*
    }

    public static Boolean isLogin() {
        if (!TextUtils.isEmpty(SPUtils.getInstance(ConstantValue.SP_NAME, MODE_PRIVATE).getString(ConstantValue.TOKEN))) {
            return true;
        } else {
            return false;
        }
    }*/

    public static void toLogin(Activity activity) {
//        activity.startActivity(new Intent(activity, LoginActivity.class));
    }

    /**
     * 手机号用****号隐藏中间数字
     *
     * @param phone
     * @return
     */
    public static String settingphone(String phone) {
        String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phone_s;
    }


    /**
     * 判断某个手机号是否存在
     */
    public static boolean isThePhoneExist(Context context, String phoneNum) {
        //uri=  content://com.android.contacts/data/phones/filter/#
        Cursor cursor = null;
        try {
            Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/" + phoneNum);
            ContentResolver resolver = context.getContentResolver();
            cursor = resolver.query(uri, new String[]{ContactsContract.Data.DISPLAY_NAME},
                    null, null, null); //从raw_contact表中返回display_name
            if (cursor.moveToFirst()) {
                //Log.i(TAG, "name=" + cursor.getString(0) + " , phoneNum = " + phoneNum);
                cursor.close();
                return true;
            }
        } catch (Exception e) {
            //Log.i(TAG, "163 e =" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return false;
    }


    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */

    public static boolean isQQClientAvailable(Context context) {

        final PackageManager packageManager = context.getPackageManager();

        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);

        if (pinfo != null) {

            for (int i = 0; i < pinfo.size(); i++) {

                String pn = pinfo.get(i).packageName;

                if (pn.equals("com.tencent.mobileqq")) {

                    return true;

                }

            }

        }

        return false;

    }

//判断微信是否可用

    public static boolean isWeixinAvilible(Context context) {

        final PackageManager packageManager = context.getPackageManager();

        // 获取packagemanager

        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);

        // 获取所有已安装程序的包信息

        if (pinfo != null) {

            for (int i = 0; i < pinfo.size(); i++) {

                String pn = pinfo.get(i).packageName;

                if (pn.equals("com.tencent.mm")) {

                    return true;

                }

            }

        }

        return false;

    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public static void callPhone(Context context, String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }

    public static void setEditFocus(EditText editText) {

        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager inputManager =
                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);
    }

    public static boolean checkWps(Context context) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage("cn.wps.moffice_eng");//WPS个人版的包名
        if (intent == null) {
            return false;
        } else {
            return true;
        }
    }

    public static void openWps(Activity activity, String path) {
        Intent intent = activity.getPackageManager().getLaunchIntentForPackage("cn.wps.moffice_eng");
        Bundle bundle = new Bundle();
        intent.setData(Uri.parse(path));//这里采用传入文档的在线地址进行打开，免除下载的步骤，也不需要判断安卓版本号
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    public static boolean openFile(Context context, String path) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString(WpsModel.OPEN_MODE, WpsModel.OpenMode.NORMAL); // 打开模式
        bundle.putBoolean(WpsModel.SEND_CLOSE_BROAD, true); // 关闭时是否发送广播
        bundle.putString(WpsModel.THIRD_PACKAGE, context.getPackageName()); // 第三方应用的包名，用于对改应用合法性的验证
        bundle.putBoolean(WpsModel.CLEAR_TRACE, true);// 清除打开记录
        // bundle.putBoolean(CLEAR_FILE, true); //关闭后删除打开文件
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setClassName(WpsModel.PackageName.NORMAL, WpsModel.ClassName.NORMAL);

        File file = new File(path);
        if (file == null || !file.exists()) {
            System.out.println("文件为空或者不存在");
            return false;
        }

        Uri uri = FileProvider.getUriForFile(context, "com.anssy.voteballot.provider", file);
//        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        intent.putExtras(bundle);
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            System.out.println("打开wps异常：" + e.toString());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void checkNetStatus(TextView textView) {
        if (NetworkUtils.isConnected()) {
            textView.setText("网络状态:已连接");
        } else {
            textView.setText("网络状态:未连接");
        }
    }

    /**
     * 复制内容到剪切板
     *
     * @param copyStr
     * @return
     */
    public static boolean copyStr(Context context, String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
